package com.ponhu.ea2.stockcenter.provider.support.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ponhu.ea2.stockcenter.properties.StockProperties;
import com.ponhu.ea2.stockcenter.provider.constants.CommonConstant;
import com.ponhu.ea2.stockcenter.provider.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private StockProperties stockProperties;
    @Autowired
    private RabbitMQService rabbitMQService;
    @Autowired
    private RedisSupportService redisSupportService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 先校验对应货品MQ缓存屏障是否存在
        if (!stockProperties.getEnablePushMqBarrier()) return;
        // 在校验是否是需要关注的 RedisKey
        if (!message.toString().contains(CommonConstant.MQ_SALESTOCK_CODE_EXP)) return;

        // 多实例部署时控制唯一实例取得执行权
        String codeKey = message.toString().replace(CommonConstant.MQ_SALESTOCK_CODE_EXP, CommonConstant.MQ_SALESTOCK_CODE);
        String mapKey = redisSupportService.bucketGetAndDel(codeKey, String.class);
        if (StringUtils.isEmpty(mapKey)) return;

        Set<Map.Entry<String, Integer>> stockEntrySet = redisSupportService.rMapEntrySet(mapKey, String.class, Integer.class);
        log.info("销售库存变动MQ缓存屏障过期 ===>> codeKey={}，mapKey={}", codeKey, mapKey);
        if (CollectionUtils.isEmpty(stockEntrySet)) return;

        redisSupportService.rMapDelete(mapKey);
        List<String> inventoryCodes = stockEntrySet.stream().map(Map.Entry::getKey).collect(Collectors.toList());
        Map<String, Integer> stockMap = stockEntrySet.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        rabbitMQService.saleStockChangeSendMsg(inventoryCodes, stockMap);
        log.info("销售库存变动MQ缓存屏障过期触发库存变动校验 ===>> codeKey={}，mapKey={}, stockMap={}",
                codeKey, mapKey, JSON.toJSONString(stockMap));
    }

}
